package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.my_order_list.chlid

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.fastjson.JSON
import com.example.library_common.album.view.grid_view.XGridLayout
import com.example.library_common.album.view.grid_view.adapter.CommAdapter
import com.example.library_common.album.view.grid_view.adapter.XQuickViewHolder
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.SstShopOrderChild
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.my_order_list.chlid.bean.OrderInfoBean
import com.example.wallet.db.UserInfoManager

class MyOrderInfoFragment : BaseFragmentEx() {

    companion object {
        fun newInstance(orderId: String): MyOrderInfoFragment {
            val args = Bundle()
            args.putString("orderId", orderId)
            val fragment = MyOrderInfoFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var orderId: String? = ""

    //收货人
    private lateinit var consigneeTv: TextView

    //电话
    private lateinit var phoneTv: TextView

    //收货地址
    private lateinit var deliveryAddress: TextView

    //订单号
    private lateinit var orderTv: TextView

    //支付时间
    private lateinit var payingTime: TextView

    //订单类型
    private lateinit var orderType: TextView

    //支付状态
    private lateinit var payStatus: TextView

    //支付方式
    private lateinit var payWay: TextView

    //实付款
    private lateinit var actualPaying: TextView

    //快递单号
    private lateinit var deliverCode: TextView

    private lateinit var mXGridLayout: XGridLayout

    private var orderInfo: OrderInfoBean? = null

    private var mAdapter: CommAdapter<SstShopOrderChild>? = null

    private val iconType = AppGlobals.getApplication().getString(R.string.wallet_sst)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        orderId = arguments?.getString("orderId", "")
    }

    override fun getLayoutId(): Any {
        return R.layout.my_order_info_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.title = "订单详情"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        consigneeTv = view.findViewById(R.id.consigneeTv)
        phoneTv = view.findViewById(R.id.phoneTv)
        deliveryAddress = view.findViewById(R.id.delivery_address)
        orderTv = view.findViewById(R.id.orderTv)
        payingTime = view.findViewById(R.id.payingTime)
        orderType = view.findViewById(R.id.orderType)
        payStatus = view.findViewById(R.id.payStatus)
        payWay = view.findViewById(R.id.payWay)
        actualPaying = view.findViewById(R.id.actualPaying)
        deliverCode = view.findViewById(R.id.deliverCode)
        mXGridLayout = view.findViewById(R.id.mXGridLayout)

        mAdapter = object :
            CommAdapter<SstShopOrderChild>(_mActivity, R.layout.my_order_info_fragment_item) {
            override fun convert(
                holder: XQuickViewHolder?,
                item: SstShopOrderChild?,
                position: Int
            ) {
                holder?.setText(R.id.name, item?.goodsName)
                    ?.setText(R.id.typeTv, "${item?.goodsColor} ${item?.goodsSize}")
                    ?.setText(R.id.priceTv, "${item?.goodsPrice}")
                    ?.setText(R.id.countTv, "x${item?.goodsNums} ")
                    ?.displayImage(R.id.icon, item?.goodsLogo)
            }

        }
        mXGridLayout.setAdapter(mAdapter, lifecycle)

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val map = mapOf(
            "orderId" to orderId,
            "uid" to userInfo?.uid
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.queryOrderInfoById)
            .success {
                parseOrderInfo(it)
            }.failure {
                Toast.makeText(_mActivity, "获取订单信息失败", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
    }

    @SuppressLint("SetTextI18n")
    private fun parseOrderInfo(it: String?) {
        val obj = JSON.parseObject(it)
        val order = obj["order"].toString()
        orderInfo = JSON.parseObject(order, OrderInfoBean::class.java)
        var cost = 0.0
        if (orderInfo?.isChild == 0) {
            cost = (orderInfo?.goodsPrice ?: 0.0) * (orderInfo?.goodsNums ?: 0)
            val child = SstShopOrderChild()
            child.createTime = orderInfo?.createTime
            child.goodsColor = orderInfo?.goodsColor
            child.goodsId = orderInfo?.goodsId ?: 0
            child.goodsLogo = orderInfo?.goodsLogo
            child.goodsName = orderInfo?.goodsName
            child.goodsNums = orderInfo?.goodsNums ?: 0
            child.goodsPrice = orderInfo?.goodsPrice ?: 0.0
            child.orderId = orderInfo?.orderId ?: 0
            child.goodsSize = orderInfo?.goodsSize
            child.orderStatus = orderInfo?.orderStatus ?: 0
            orderInfo?.childOrds?.add(child)

        } else if (orderInfo?.isChild == 1) {

            for (en in orderInfo?.childOrds ?: emptyList<SstShopOrderChild>()) {
                cost += en.goodsPrice * en.goodsNums
            }
        }

        actualPaying.text = "$cost ${orderInfo?.tokenType}"

        mAdapter?.addAll(orderInfo?.childOrds)
        mXGridLayout.maxItem = orderInfo?.childOrds?.size ?: 0

        presentData()
    }

    private fun presentData() {
        consigneeTv.text=orderInfo?.receiverName

        phoneTv.text=orderInfo?.receiverPhone

        deliveryAddress.text=orderInfo?.receiverAddr

        orderTv.text=orderInfo?.orderNo.toString()

        payingTime.text=orderInfo?.createTime
        //1 商城；2团购；3秒杀
        orderType.text=when(orderInfo?.orderType){
            1->"商城"
            2->"团购"
            3->"秒杀"
            else->""
        }
        payStatus.text=when(orderInfo?.payType){
            1->"已支付"
            else->"已支付"
        }
        payWay.text=when(orderInfo?.payType){
            1->"余额支付"
            else->"余额支付"
        }

        deliverCode.text=orderInfo?.expressNo
    }
}